<?php

namespace app\api\controller;

use app\BaseController;
use frame\lib\Db;
use frame\lib\VerfiyParam;

class Comment extends Base
{
  
   public function add()
   {
      $param = $_POST;
      $rule = ['id|文章ID' => 'require|int', 'comment|评论内容' => 'require|min:5'];
      VerfiyParam::init($param, $rule);
      $user_id = $this->user_id;
      $uid = $this->uid;
      $art = Db::name('article')->where(['id' => $param['id'], 'user_id' => $user_id, 'delete_time' => 0])->find();
      if (!$art) error('文章不存在');
      if ($art['status'] == 0) error('文章待审核');
      request_limit('comment', "uid = $uid", 10);
      $data = [
         'comment' => $param['comment'],
         'art_id' => $param['id'],
         'uid' => $this->uid,
         'user_id' => $this->user_id,
         'create_time' => getTime()
      ];
      Db::name('article')->where(['id' => $param['id'], 'user_id' => $user_id, 'delete_time' => 0])->update(['comment' => ++$art['comment']]);
      $res = Db::name('comment')->insert($data);
      if ($res)   success();
      error();
   }
   // 我的评论
   public function mine()
   {
      $uid = $this->uid;
      $sql = " select c.id ,a.id  as art_id ,title , c.uid,c.comment ,c.create_time  from article as a,comment as c 
         where a.id = c.art_id && c.uid = $uid && c.delete_time = 0;";
      $list = Db::query($sql);
      success($list);
   }
   public function del()
   {
      $id = @$_GET['id'];
      $com = Db::name('comment')->where(['uid' => $this->uid, 'id' => $id, 'delete_time' => 0])->find();
      if (!$com)  error('评论不存在');
      $res = Db::name('comment')->where(['uid' => $this->uid, 'id' => $id])->delete();
      if ($res) success();
      error();
   }
}
